﻿using System.Windows;
using System.Collections.Specialized;
using System.Windows.Controls;
using System.IO;
using System.Reflection;

namespace Com.CodePlex.SPPower.View {

	public partial class MainWindowView : Window {

		public ViewModel.MainWindowViewModel ViewModel {
			get { return (ViewModel.MainWindowViewModel)DataContext; }
		}

		public MainWindowView() {
			InitializeComponent();
			Closing += (s, e) => {
				if (ViewModel.WarnExit()) {
					MessageBoxResult result = MessageBox.Show("Are you sure?", "Warning", MessageBoxButton.YesNo, MessageBoxImage.Question);
					if (result == MessageBoxResult.No) {
						e.Cancel = true;
					}
				}
				if (!e.Cancel) {
					ViewModel.Exit();
				}
			};
			Loaded += (s, e) => {
				ViewModel.Load();
				ViewModel.History.CollectionChanged += (s1, e1) => {
					historyScroll.ScrollToEnd();
				};
				ViewModel.RequestExit += (s1, e1) => {
					Close();
				};
			};
			treeView1.SelectedItemChanged += (s, e) => {
				ViewModel.SelectCmd(treeView1.SelectedValue);
			};
		}
	}

	public class MainWindowViewHelper : DependencyObject {

		public static readonly DependencyProperty IsAutoScrollProperty = DependencyProperty.RegisterAttached("IsAutoScroll", 
			typeof(bool),
			typeof(MainWindowViewHelper), 
			new UIPropertyMetadata(default(bool),OnIsAutoScrollChanged));

		
		public static bool GetIsAutoScroll(DependencyObject obj) {
			return (bool)obj.GetValue(IsAutoScrollProperty);
		} 

		public static void SetIsAutoScroll(DependencyObject obj, bool value) {
			obj.SetValue(IsAutoScrollProperty, value);
		}

		public static void OnIsAutoScrollChanged(DependencyObject s, DependencyPropertyChangedEventArgs e) {
			TextBox textbox = s as TextBox;
			var eventh = new TextChangedEventHandler((s1, e1) => {
				textbox.ScrollToEnd();
			});
			var eventh1 = new DependencyPropertyChangedEventHandler((s1, e1) => {
				textbox.ScrollToEnd();
			});
			if ((bool)e.NewValue) {
				textbox.TextChanged += eventh;
				textbox.DataContextChanged += eventh1;
			} else {
				textbox.TextChanged -= eventh;
				textbox.DataContextChanged -= eventh1;
			}
		}
	}
}
